<?php

namespace App\Http\Controllers;

use App\Models\Material;
use App\Models\Type;
use App\Models\OperationLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class MaterialController extends Controller
{
    /**
     * 构造函数，设置中间件
     */
    public function __construct()
    {
        $this->middleware('auth');
        // 只有管理员可以执行创建、编辑、删除操作
        $this->middleware('role:admin')->only(['create', 'store', 'edit', 'update', 'destroy']);
    }

    /**
     * 显示材料列表
     */
    public function index()
    {
        $query = Material::with('type');

        // 搜索条件
        if (request('search')) {
            $search = request('search');
            $query->where(function($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('purpose', 'like', "%{$search}%")
                  ->orWhere('remark', 'like', "%{$search}%");
            });
        }

        if (request('type_id')) {
            $query->where('type_id', request('type_id'));
        }

        $materials = $query->orderBy('created_at', 'desc')->paginate(10);
        $types = \App\Models\Type::all();

        return view('materials.index', compact('materials', 'types'));
    }

    /**
     * 显示创建材料表单
     */
    public function create()
    {
        $types = Type::all();
        return view('materials.create', compact('types'));
    }

    /**
     * 保存新创建的材料
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:100',
            'type_id' => 'required|exists:types,id',
            'unit' => 'required|string|max:20',
            'quantity' => 'required|numeric|min:0',
            'purpose' => 'nullable|string|max:200',
            'remark' => 'nullable|string'
        ]);

        $material = Material::create($request->all());

        // 记录操作日志
        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'create',
            'target_type' => 'material',
            'target_id' => $material->id,
            'content' => "创建材料：{$material->name}",
            'ip' => $request->ip()
        ]);

        return redirect()->route('materials.index')->with('success', '材料创建成功');
    }

    /**
     * 显示材料详情
     */
    public function show(Material $material)
    {
        return view('materials.show', compact('material'));
    }

    /**
     * 显示编辑材料表单
     */
    public function edit(Material $material)
    {
        $types = Type::all();
        return view('materials.edit', compact('material', 'types'));
    }

    /**
     * 更新材料信息
     */
    public function update(Request $request, Material $material)
    {
        $request->validate([
            'name' => 'required|string|max:100',
            'type_id' => 'required|exists:types,id',
            'unit' => 'required|string|max:20',
            'purpose' => 'nullable|string|max:200',
            'remark' => 'nullable|string'
        ]);

        $material->update($request->all());

        // 记录操作日志
        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'update',
            'target_type' => 'material',
            'target_id' => $material->id,
            'content' => "更新材料：{$material->name}",
            'ip' => $request->ip()
        ]);

        return redirect()->route('materials.index')->with('success', '材料更新成功');
    }

    /**
     * 删除材料
     */
    public function destroy(Material $material)
    {
        // 记录操作日志
        OperationLog::create([
            'user_id' => Auth::id(),
            'action' => 'delete',
            'target_type' => 'material',
            'target_id' => $material->id,
            'content' => "删除材料：{$material->name}",
            'ip' => request()->ip()
        ]);

        $material->delete();

        return redirect()->route('materials.index')->with('success', '材料删除成功');
    }

    /**
     * 导出材料数据
     */
    public function export(Request $request)
    {
        $query = Material::with('type');

        // 应用搜索条件
        if ($request->has('search')) {
            $query->where('name', 'like', '%' . $request->search . '%');
        }

        if ($request->has('type_id')) {
            $query->where('type_id', $request->type_id);
        }

        if ($request->has('stock_status')) {
            if ($request->stock_status === 'low') {
                $query->where('quantity', '<=', 10);
            } elseif ($request->stock_status === 'normal') {
                $query->where('quantity', '>', 10);
            }
        }

        $materials = $query->get();

        // 生成CSV文件
        $filename = 'materials_' . date('Y-m-d_His') . '.csv';
        $headers = [
            'Content-Type' => 'text/csv',
            'Content-Disposition' => 'attachment; filename="' . $filename . '"',
        ];

        $callback = function() use ($materials) {
            $file = fopen('php://output', 'w');
            
            // 添加UTF-8 BOM
            fprintf($file, chr(0xEF).chr(0xBB).chr(0xBF));
            
            // 添加表头
            fputcsv($file, ['ID', '材料名称', '类型', '单位', '库存数量', '用途', '备注', '创建时间', '更新时间']);
            
            // 添加数据
            foreach ($materials as $material) {
                fputcsv($file, [
                    $material->id,
                    $material->name,
                    $material->type->name,
                    $material->unit,
                    $material->quantity,
                    $material->purpose,
                    $material->remark,
                    $material->created_at->format('Y-m-d H:i:s'),
                    $material->updated_at->format('Y-m-d H:i:s')
                ]);
            }
            
            fclose($file);
        };

        return response()->stream($callback, 200, $headers);
    }
} 